import axios from 'axios';
import { storage } from '@/utils/storage.utils';
const retryPath = ['/apx-game/home/petInfo/query', '/apx-auth/thirdPartyAuth/twitter/game/getApxToken'];
import {ERROR_MESSAGE} from "@/constant/error-message";
const cancelToken = false;
// // 临时测试用token
// const provisional_token =
//   'eyJhbGciOiJIUzUxMiJ9.eyJleHBpcmF0aW9uVGltZSI6MTcwOTcxMjk2MjQ1MSwidXNlcklkIjoyfQ.MiM3QYQzfMCgOaw_bNr_4xvi4bT5bqSFqUAODhHKj7oaputXAz86EBnI1j_mBagYZdYCYUapHoI-ghPJ2Q4KIw';
const baseUrl= import.meta.env.VITE_APP_BASE_URL;
const http = axios.create({
    baseURL: baseUrl,
    timeout: 30000,
});

http.interceptors.request.use(async (config) => {
    const token = storage.get<String>('apex_token');
    config.headers['Access-Control-Allow-Origin'] = '*';
    config.headers['Access-Control-Allow-Credentials'] = true;
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token;
    }

    // if (config.url.includes('twitter/requestToken')) {
    //     cancelToken = false;
    // }
    return cancelToken ? Promise.reject('request cancel') : config;
});

http.interceptors.response.use(
    (res) => {
        // if (res.config.loading) $Dialog.close();
        return res;
    },
    (err) => {
        console.log(err);
        // if (err?.config?.loading) $Dialog.close();
        // 如果在retry重要请求中，重新执行请求和逻辑
        if (err?.config?.url) {
            if (retryPath.includes(err?.config?.url)) {
                // $Dialog.open({
                //     type: 'alert',
                //     title: 'Your network seems to have gone absent without leave :), please reloading',
                //     okClick: () => {
                //         if (err.config.url === '/apx-game/home/petInfo/query') {
                //             // 重新渲染一遍home组件
                //             commonStore.hasLogin = false;
                //             setTimeout(() => {
                //                 commonStore.hasLogin = true;
                //             }, 1);
                //         } else if (err.config.url === '/apx-auth/thirdPartyAuth/twitter/game/getApxToken') {
                //             // 重新执行token校验
                //             commonStore.refresh = true;
                //         }
                //     },
                // });
            } else {
                // $Dialog.open({
                //     type: 'msgErr',
                //     title: 'Service Unavailable',
                // });
            }
        }
    },
);

export default http;
